package avicit.bdp.dcs.rule.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.dcs.rule.dao.ColumnRuleDao;
import avicit.bdp.dcs.rule.dto.ColumnRuleDTO;
import avicit.bdp.dcs.task.dto.TaskDTO;
import avicit.bdp.dcs.task.service.TaskService;
import avicit.bdp.dcs.tools.enums.RuleType;
import avicit.bdp.dcs.utils.DcsErrorCode;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.core.exception.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @金航数码科技有限责任公司
 * @作者：liyb
 * @邮箱：liyb@avic-digital.com
 * @创建时间：2020-08-06 14:00
 * @类说明：
 * @修改记录：
 */
@Service
@Transactional
public class ColumnRuleService extends BaseService<ColumnRuleDao, ColumnRuleDTO> {

  @Autowired private TaskService taskService;

  public String saveColumnRule(ColumnRuleDTO columnRuleDTO) throws Exception {
    TaskDTO taskDTO = taskService.selectByPrimaryKey(columnRuleDTO.getTaskId());
    if (taskDTO == null) {
      throw new BusinessException(
          String.format(DcsErrorCode.TASK_NULL.getDesc(), columnRuleDTO.getTaskId()));
    }

    columnRuleDTO.setId(ComUtil.getId());
    columnRuleDTO.setName("修改规则");
    this.insert(columnRuleDTO);
    BdpLogUtil.log4Insert(columnRuleDTO);
    return this.buildColumnRuleName(columnRuleDTO, taskDTO);
  }

  public String deleteColumnRuleById(String columnRuleId) throws Exception {
    this.deleteByPrimaryKey(columnRuleId);
    return null;
  }

  public List<ColumnRuleDTO> getColumnRuleListByTaskId(String taskId) throws Exception {
    TaskDTO taskDTO = taskService.selectByPrimaryKey(taskId);
    if (taskDTO == null) {
      throw new BusinessException(String.format(DcsErrorCode.TASK_NULL.getDesc(), taskId));
    }

    ColumnRuleDTO columnRuleDTOQuery = new ColumnRuleDTO();
    columnRuleDTOQuery.setTaskId(taskId);
    List<ColumnRuleDTO> columnRuleList = this.selectList(columnRuleDTOQuery);
    if (CollectionUtils.isNotEmpty(columnRuleList)) {
      for (ColumnRuleDTO columnRule : columnRuleList) {
        columnRule.setName(this.buildColumnRuleName(columnRule, taskDTO));
      }
    }
    return columnRuleList;
  }

  /**
   * 构建规则名称
   *
   * @param columnRuleDTO
   * @param taskDTO
   * @return
   */
  private String buildColumnRuleName(ColumnRuleDTO columnRuleDTO, TaskDTO taskDTO) {
    StringBuilder builder = new StringBuilder();
    builder.append(columnRuleDTO.getName()).append(":表名").append(taskDTO.getDstTableName());

    // 规则类型，添加前后缀：1
    if (RuleType.PREFIX_SUFFIX.getCode() == columnRuleDTO.getRuleType()) {
      builder
          .append("列名添加前缀:")
          .append(columnRuleDTO.getPrefix())
          .append(",后缀:")
          .append(columnRuleDTO.getSuffix());
    }
    return builder.toString();
  }
}
